package common;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public abstract class SimpleXMLGenerator
{
    protected TransformerHandler handler;

    public SimpleXMLGenerator(String file_path, String file_name_no_ext)
    {
        SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        try
        {
            handler = factory.newTransformerHandler();
            Transformer transformer = handler.getTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            File output = FSUtils.createFile(file_path, file_name_no_ext + ".xml");
            Result result = new StreamResult(new FileOutputStream(output));
            handler.setResult(result);
        } catch (TransformerConfigurationException e)
        {
            e.printStackTrace();
            System.out.println("Error in getting Transformer Handler.");
            System.exit(-1);
        } catch (IOException e)
        {
            e.printStackTrace();
            System.out.println("Error in creating output file.");
            System.exit(-1);
        }
        instance = new AttributesImpl();
    }

    public abstract void generate() throws SAXException;

    public AttributesImpl instance;

    public AttributesImpl getAttrImplInstance()
    {
        instance.clear();
        return instance;
    }

    public void openElement(String qName, AttributesImpl attr) throws SAXException
    {
        handler.startElement("", "", qName, attr);
    }

    public void openElement(String qName) throws SAXException
    {
        openElement(qName, null);
    }

    public void closeElement(String qName) throws SAXException
    {
        handler.endElement("", "", qName);
    }

    public void setContent(String content) throws SAXException
    {
        if (content == null)
            return;
        handler.characters(content.toCharArray(), 0, content.length());
    }
}
